﻿Imports System.Threading
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Xml

Imports HtmlAgilityPack
Imports System.Reflection
Imports System.Threading.Tasks

Public Class Main
    Private Shared OnlineTimeout = 1500
    Private RTMPDumpPath As String = "rtmpdump.exe"

    Public Shared Stream_rtmp As String = "rtmp://own3duslivefs.fplive.net:1935/own3duslive-live"
    Public Shared Stream_tcUrl As String = "rtmp://own3duslivefs.fplive.net:1935/own3duslive-live"
    Public Shared Stream_PlaypathPrefix As String = "own3d."

    Private Class LeagueStreamer
        Public Property StreamerName As String
        Public Property PlayPath As String
    End Class

    Public Function CheckPlayPathOnline(PlayPath As String) As Boolean
        Dim TempPath As String = Path.GetTempPath() & PlayPath & ".flv"
        Dim Process As New Process
        Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
        Process.StartInfo.FileName = RTMPDumpPath
        Process.StartInfo.Arguments = _
            "--rtmp " & Stream_rtmp & " " & _
            "--tcUrl " & Stream_tcUrl & " " & _
            "--playpath " & Stream_PlaypathPrefix & "" & PlayPath & " " & _
            "--live " & _
            "-o """ & TempPath & """"
        Process.Start()

        Dim VideoInfo As FileInfo = Nothing
        Dim TimeDelayed = 0
        While TimeDelayed < OnlineTimeout
            Thread.Sleep(250)
            TimeDelayed += 250
            Try
                VideoInfo = New FileInfo(TempPath)
                VideoInfo.Refresh()
                If VideoInfo.Length = 0 Then
                    VideoInfo = Nothing
                Else
                    Exit While
                End If
            Catch ex As Exception
                Debug.WriteLine(ex.Message)
            End Try
        End While

        If Not Process.HasExited Then Process.Kill()
        Process.WaitForExit()
        Try
            File.Delete(TempPath)
        Catch
        End Try

        Return Not (VideoInfo Is Nothing OrElse VideoInfo.Length = 0)
    End Function

    Public Sub CheckSelectionOnline()
        Dim CheckThread As New Thread(
            Sub(Frm As Form)
                Dim PlayPath As String = ""
                Frm.Invoke(Sub() PlayPath = DirectCast(ComboBoxStreams.SelectedItem, LeagueStreamer).PlayPath)

                Frm.Invoke(Sub() LabelIsOnline.Text = "Checking...")
                Dim Result As Boolean = CheckPlayPathOnline(PlayPath)
                Dim IsOnline As String = IIf(Result, "Online", "Offline")
                Frm.Invoke(
                    Sub()
                        ' Only continue of the one selected is currently active
                        If PlayPath = DirectCast(ComboBoxStreams.SelectedItem, LeagueStreamer).PlayPath Then
                            LabelIsOnline.Text = IsOnline
                            ButtonLaunch.Enabled = Result
                        End If
                    End Sub)
            End Sub)

        CheckThread.Start(Me)
    End Sub

    Private Sub ButtonLaunch_Click(sender As System.Object, e As System.EventArgs) Handles ButtonLaunch.Click
        Dim Process As New Process
        Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
        Process.StartInfo.FileName = "cmd.exe"
        Process.StartInfo.Arguments = _
            "/C echo """" | """ & RTMPDumpPath & """ --rtmp " & Stream_rtmp & " " & _
            "--tcUrl " & Stream_tcUrl & " " & _
            "--playpath """ & Stream_PlaypathPrefix & DirectCast(ComboBoxStreams.SelectedItem, LeagueStreamer).PlayPath & """ " & _
            "--live " & _
            "| """ & VLCHelper.GetPath() & """ - "

        Process.Start()
    End Sub

    Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim Frm As New About
        Frm.ShowDialog(Me)
    End Sub

    Private Sub PopulateStreamers()
        Dim Req = WebRequest.Create(My.Settings.StreamList)
        Dim Resp As WebResponse
        Try
            Resp = Req.GetResponse()
        Catch
            MsgBox("Could not fetch list of streamers. Verify that you are connected to the internet.", vbExclamation Or vbOKOnly, "League Stream Manager")
            Exit Sub
        End Try

        Dim Reader As StreamReader = New StreamReader(Resp.GetResponseStream(), Encoding.GetEncoding(1252))
        Dim HTML As String = Reader.ReadToEnd()
        Reader.Close()

        Resp.Close()

        Dim Doc As New HtmlDocument
        Doc.LoadHtml(HTML)

        ComboBoxStreams.Items.Clear()

        Dim Rows = Doc.DocumentNode.SelectNodes("//table[tr/th = 'Player']/tr[not (th)]")
        If Rows Is Nothing OrElse Rows.Count = 0 Then
            MsgBox("The list of streams was not correctly formed. It must contain a table with the headings ""Player"" and ""PlayPath"".", vbExclamation Or vbOKOnly, "League Stream Manager")
            Exit Sub
        End If

        Dim StreamerList As New List(Of LeagueStreamer)
        Parallel.ForEach(Rows,
                         Sub(Row As HtmlNode)
                             Dim Streamer As New LeagueStreamer
                             Streamer.StreamerName = Row.SelectSingleNode("td[1]").InnerText
                             Streamer.PlayPath = Row.SelectSingleNode("td[2]").InnerText

                             Dim IsOnline As Boolean = CheckPlayPathOnline(Streamer.PlayPath)
                             If IsOnline Then
                                 Streamer.StreamerName &= " (Online)"
                             End If
                             StreamerList.Add(Streamer)
                         End Sub)

        ComboBoxStreams.Items.AddRange(StreamerList.ToArray())

        Dim RTMPRow = Doc.DocumentNode.SelectSingleNode("//table[tr/th = 'Property']/tr[td[1] = 'rtmp']/td[2]")
        If RTMPRow IsNot Nothing Then
            Stream_rtmp = RTMPRow.InnerText
        End If
        Dim TcUrlRow = Doc.DocumentNode.SelectSingleNode("//table[tr/th = 'Property']/tr[td[1] = 'tcUrl']/td[2]")
        If TcUrlRow IsNot Nothing Then
            Stream_tcUrl = TcUrlRow.InnerText
        End If
        Dim PlaypathPrefixRow = Doc.DocumentNode.SelectSingleNode("//table[tr/th = 'Property']/tr[td[1] = 'Playpath prefix']/td[2]")
        If PlaypathPrefixRow IsNot Nothing Then
            Stream_PlaypathPrefix = PlaypathPrefixRow.InnerText
        End If
    End Sub

    Private Sub Main_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        ' Extract RTMPDump
        Dim Asm = Assembly.GetExecutingAssembly()
        Dim Resource As Stream = Asm.GetManifestResourceStream("LeagueStreamManager.rtmpdump.exe")
        RTMPDumpPath = Path.GetTempPath() & "rtmpdump.exe"
        Dim fs = New FileStream(RTMPDumpPath, FileMode.Create, FileAccess.Write)
        Dim writeResource = New BinaryWriter(fs)
        Dim buffer(Resource.Length) As Byte
        Resource.Read(buffer, 0, Resource.Length)
        writeResource.Write(buffer)
        writeResource.Close()

        PopulateStreamers()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Close()
    End Sub

    Private Sub OptionsToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles OptionsToolStripMenuItem.Click
        Dim Options As New Options
        If Options.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            PopulateStreamers()
        End If
    End Sub

    Private Sub ComboBoxStreams_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBoxStreams.SelectedIndexChanged
        ButtonLaunch.Enabled = False
        CheckSelectionOnline()
    End Sub

    Private Sub Main_FormClosed(sender As System.Object, e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        File.Delete(RTMPDumpPath)
    End Sub
End Class
